package com.imooc.rabbitmq.utils;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConnectionUtils {
    /**
     * 获取MQ连接
     * @return
     */
    public static Connection getConnection() throws IOException, TimeoutException {
        return getConnection("127.0.0.1",5672,"/vhost_mmr","user_mmr","mmr");
    }

    public static Connection getConnection(String host,Integer port,String vhost,String username,String passwd) throws IOException, TimeoutException {
        //定义一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务器地址
        factory.setHost(host);

        //AMQP 5672
        factory.setPort(port);

        //vhost
        factory.setVirtualHost(vhost);

        //用户名
        factory.setUsername(username);

        //密码
        factory.setPassword(passwd);

        //自动重连
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(3000);
        return factory.newConnection();
    }
}
